import net from "net";
import { TcpSocket } from "./TcpSocket";

/**
 * 封装的Tcp服务端
 */
export class TcpServer {

    svr: net.Server;

    private _onSocket: (socket: TcpSocket) => void;

    constructor(port: number, onStart: () => void, onSocket: (socket: TcpSocket) => void) {
        this._onSocket = onSocket;
        this.svr = net.createServer(this.onSocket.bind(this));
        this.svr.on("error", this.onError.bind(this));
        this.svr.listen(port, onStart);
    }

    private onError(err: Error) {
        console.error(err);
        process.exit();
    }

    private onSocket(socket: net.Socket) {
        this._onSocket(new TcpSocket(socket));
    }
}